package com.bw.controller;

import cn.hutool.core.util.StrUtil;
import com.bw.common.JwtUtils;
import com.bw.common.Md5Utils;
import com.bw.entity.User;
import com.bw.mapper.UserMapper;
import com.bw.service.UserService;
import lombok.AllArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.util.List;

@Controller
public class LoginController {


    @Autowired
    UserService userService;

    /**
     * 登录页面
     *
     * @return
     */
    @RequestMapping("/loginPage.do")
    public String loginPage() {

        return "login";

    }

    /**
     * jsr303
     * 执行登录
     *
     * @param loginUser
     * @param model
     * @param request
     * @return
     */
    @RequestMapping("/login.do")
    public String login(@Valid User loginUser, BindingResult result, Model model, HttpServletRequest request, HttpServletResponse response) {
        //1. 非空验证
        if (result.hasErrors()) {
            model.addAttribute("error", result.getAllErrors().get(0).getDefaultMessage());
            return "login";
        }
        //2. 用户名是否存在

        User userFromDB = userService.selectByName(loginUser.getName());
        if (userFromDB == null){
            model.addAttribute("error", "用户名不存在");
            return "login";
        }

        // 3. 密码是否正确

        String loginUserPassword = loginUser.getPassword(); // 用户输入的密码  明文

        String password = userFromDB.getPassword();// 数据库的密码  密文乱码
        String salt = userFromDB.getSalt(); // 数据库的盐


        String md5String = Md5Utils.getMD5String(loginUserPassword + salt); // 密文乱码


        if (!md5String.equals(password)){
            model.addAttribute("error", "密码错误");
            return "login";
        }

        // 把用户放到session 里
//        request.getSession().setAttribute("user",userFromDB);
        // 加密用户
        String token = JwtUtils.createToken(userFromDB);
        //把令牌放到cookie里
        Cookie cookie = new Cookie("token", token);

        response.addCookie(cookie);
        return "redirect:list.do";

    }
}
